package store

import (
	"../../deps/lessgo/data/redis"
	"../../deps/lessgo/utils"
	"../conf"
	"fmt"
	"os/exec"
	"strings"
	"time"
)

var connector *redis.Connector

func Initialize() error {

	var err error

	if serverPid() == "" {

		if err := serverStart(); err != nil {
			return err
		}
	}

	if connector, err = redis.NewConnector(conf.StoreServerConf); err != nil {
		// Retry later ...
		time.Sleep(5e8)
		connector, err = redis.NewConnector(conf.StoreServerConf)
	}

	go func() {

		for {

			time.Sleep(1e9)

			randValue := utils.StringNewRand(10)
			Cmd("SETEX", "tmp:health_tracker", 2, randValue)
			if randValue == Cmd("GET", "tmp:health_tracker").String() {
				continue
			}

			fmt.Println("store server error")

			if pid := serverPid(); pid != "" {
				exec.Command("/bin/kill", "-9", pid)
				time.Sleep(1e9)
			}

			serverStart()
			time.Sleep(1e9)
			//connector, _ = redis.NewConnector(conf.StoreServerConf)
		}
	}()

	return err
}

func Cmd(cmd string, args ...interface{}) *redis.Reply {
	return connector.Cmd(cmd, args...)
}

func serverPid() string {

	pid, err := exec.Command("/bin/ps", "aux",
		"|", "grep", conf.StoreServerName,
		"|", "grep", "-v", "grep",
		"|", "awk", "'{print $2}'").Output()
	if err != nil {
		return ""
	}

	return string(pid)
}

func serverStart() error {
	return exec.Command(conf.StoreServerPath, strings.Fields(conf.StoreServerArgs)...).Run()
}
